import { CollectionMetadataType, DatasetCollectionSchemaType } from '@/types/dataset';
import { Button, Descriptions, Divider } from 'antd';
import dayjs from 'dayjs';
import { memo, useCallback, useEffect, useState } from 'react';
import datasetService from '@/api/services/datasetService';
import Indexes from './Indexes';
import { DatasetCollectionTypeMap, TrainingTypeMap } from '@/types/enum';
import { useContextSelector } from 'use-context-selector';
import { CollectionContext } from '../../context';
import { PlusOutlined } from '@ant-design/icons';
import Metadatas from './metadatas';
import { formatFileSize } from '@/utils/format-number';

const Metadata = () => {
  // const [data, setData] = useState<DatasetCollectionSchemaType | null>(null);
  const { collectionId, collectionData, setCollectionData } = useContextSelector(
    CollectionContext,
    (s) => s,
  );

  const handleAddIndex = (index: string) => {
    setCollectionData((prev) => {
      if (!prev) {
        return null;
      }
      return {
        ...prev,
        indexes: [...(prev.indexes ?? []), index],
      };
    });
  };
  const handleUpdateMetadata = (metadata: CollectionMetadataType) => {
    setCollectionData((prev) => {
      if (!prev) {
        return null;
      }
      return {
        ...prev,
        metadata: { ...metadata },
      };
    });
  };

  const handleRemoveIndex = (index: string) => {
    setCollectionData((prev) => {
      if (!prev) {
        // 如果 `prev` 是 null，直接返回 null
        return null;
      }

      // 返回一个新对象，其中的 indexes 数组不包含要移除的 index
      return {
        ...prev,
        indexes: prev.indexes?.filter((i) => i !== index),
      };
    });
  };

  const getDatas = useCallback(async () => {
    try {
      const res = await datasetService.collectionDetail(collectionId);
      setCollectionData(res);
    } catch (error) {
      console.log(error);
    }
  }, [collectionId]);

  useEffect(() => {
    if (collectionId) {
      getDatas();
    }
  }, [collectionId]);

  return (
    <div
      className="ml-2 h-full w-full overflow-y-auto rounded-xl bg-[#FFF]"
      style={{ scrollbarWidth: 'none' }}
    >
      <div className="p-4">
        <Descriptions title="元数据" column={1}>
          <Descriptions.Item label="集合名">{collectionData?.name}</Descriptions.Item>
          <Descriptions.Item label="集合ID">{collectionData?._id}</Descriptions.Item>
          <Descriptions.Item label="类型">
            {collectionData?.type ? DatasetCollectionTypeMap[collectionData?.type].name : '-'}
          </Descriptions.Item>
          <Descriptions.Item label="来源大小">
            {collectionData?.file ? formatFileSize(collectionData?.file.length) : '-'}
          </Descriptions.Item>
          <Descriptions.Item label="原文长度">{collectionData?.rawTextLength}</Descriptions.Item>
          <Descriptions.Item label="训练模式">
            {collectionData?.trainingType
              ? TrainingTypeMap[collectionData?.trainingType].name
              : '-'}
          </Descriptions.Item>
          <Descriptions.Item label="分割大小">{collectionData?.chunkSize}</Descriptions.Item>
          <Descriptions.Item label="分割数组">mode</Descriptions.Item>
          <Descriptions.Item label="导入时间">
            {dayjs(collectionData?.createTime).format('YYYY-MM-DD HH:mm:ss')}
          </Descriptions.Item>
          <Descriptions.Item label="更新时间">
            {dayjs(collectionData?.updateTime).format('YYYY-MM-DD HH:mm:ss')}
          </Descriptions.Item>
        </Descriptions>
        {/* <Divider orientation="left" dashed>
          <span className="text-xs">自定义元数据</span>
        </Divider> */}
        <div style={{ marginTop: '16px', fontWeight: 'bold', fontSize: '16px' }}>自定义元数据</div>
        <Metadatas
          collectionId={collectionData?._id}
          metadata={collectionData?.metadata ?? {}}
          addMetadata={handleUpdateMetadata}
          removeMetadata={handleUpdateMetadata}
        />
        {/* <Divider orientation="left" dashed>
          <span className="text-xs">自定义额外索引</span>
        </Divider> */}
        <div
          style={{ marginTop: '16px', fontWeight: 'bold', fontSize: '16px', marginBottom: '20px' }}
        >
          自定义额外索引
        </div>
        <Indexes
          collectionId={collectionData?._id}
          indexes={collectionData?.indexes ?? []}
          addIndex={handleAddIndex}
          removeIndex={handleRemoveIndex}
        />
      </div>
    </div>
  );
};

export default memo(Metadata);
